package com.situ.mall.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.common.entity.Cart;
import com.situ.mall.common.entity.Member;
import com.situ.mall.common.exception.NoLoginException;
import com.situ.mall.common.mapper.CartMapper;
import com.situ.mall.common.service.ICartService;
import com.situ.mall.common.util.RequestUtil;
import com.situ.mall.common.vo.CartVO;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kkkkkk
 * @since 2023-09-15
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Override
    public void addToCart(Integer pId) {
        Object o = RequestUtil.getCurrent();
        if (o == null) {
            throw new NoLoginException();
        }
        Member m = (Member) o;
        Cart c2 = baseMapper.selectOne(new LambdaQueryWrapper<Cart>().eq(Cart::getProductId, pId).eq(Cart::getMemberId, m.getId()));
        if (c2 == null) {
            Cart c = new Cart();
            c.setAmount(1);
            c.setCreatetime(LocalDateTime.now());

            c.setMemberId(m.getId());
            c.setProductId(pId);

            baseMapper.insert(c);
        } else {
            c2.setAmount(c2.getAmount() + 1);
            baseMapper.updateById(c2);
        }
    }

    @Override
    public List<CartVO> cartList() {
        Member o = (Member) RequestUtil.getCurrent();
        return baseMapper.cartList(o.getId(), null);
    }

    @Override
    public List<CartVO> selectByIds(String ids) {
        return baseMapper.cartList(null, ids.split(","));
    }
}
